package com.jn.algorithm.day003.question8;

/**
 * 字符串转换整数
 *
 * @author 江南大学1033190417
 * @date 2022/4/17 10:38
 */
public class Solution {

    public int myAtoi(String s) {
        s = s.trim();
        StringBuilder str = new StringBuilder();
        boolean fuhao = false;//默认正数
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            if (i == 0) {
                if (c == '+') {
                } else if (c == '-')
                    fuhao = true;
                else if (c >= '0' && c <= '9') {
                    str.append(c);
                } else {
                    return 0;
                }
            } else {
                if (c >= '0' && c <= '9') {
                    str.append(c);
                }else
                    break;
            }
        }
        if (str.length()==0)
            return 0;
        try {
            int parseInt = Integer.parseInt(str.toString());
            if (fuhao){
                return -parseInt;
            }else
                return parseInt;
        }catch (Exception e){
            if (fuhao){
                return -Integer.MIN_VALUE;
            }else
                return Integer.MAX_VALUE;
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.myAtoi("    "));
        System.out.println(-Integer.MIN_VALUE);
    }
}
